package com.luyuan.crm.member.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.model.DataModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.MemberGroup;
import com.luyuan.crm.member.model.MemberIntegral;
import com.luyuan.crm.member.model.MemberLevel;
import com.luyuan.crm.member.service.MemberIntegralService;
import com.luyuan.crm.member.service.MemberService;
import com.luyuan.crm.sms.service.SmsService;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.query.criteria.RestrictionTemplate;
import com.ruijie.foundation.security.AppUserContext;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.web.jsf.context.TableContext;
import com.ruijie.web.jsf.model.PageDataModel;
import com.ruijie.web.jsf.model.TableOrder;
import com.ruijie.web.jsf.model.TablePage;

@Component("memberAction")
@Scope("view")
public class MemberAction extends BaseAction implements InitializingBean {

    private final static Log logger = LogFactory.getLog(MemberAction.class);

    @Resource(name = "memberService")
    private MemberService memberService;

    @Resource(name = "memberIntegralService")
    private MemberIntegralService memberIntegralService;

    @Resource(name = "smsService")
    private SmsService smsService;

    private String smsContent;

    public String getSmsContent() {
        return smsContent;
    }

    public void setSmsContent(String smsContent) {
        this.smsContent = smsContent;
    }

    // 查询条件
    private Member criteria = new Member();

    private MemberLevel levelCriteria;

    private MemberGroup groupCriteria;

    private Date startDate;

    private Date endDate;

    // 添加或编辑模型
    private Member memberModel = null;

    private MemberIntegral memberIntegral = null;

    private String memberId;

    public Member getMemberModel() {
        return memberModel;
    }

    public void reloadMember() {
        if (memberId != null && !"".equals(memberId)) {
            memberModel = memberService.getById(memberId);
        }
        if (memberModel == null) {
            memberModel = memberService.getByAccount((AppUser) AppUserContext.getCurrentUser());
        }
        if (memberModel == null) {
            memberModel = new Member();
        }
    }

    public MemberIntegral getMemberIntegral() {
        if (memberIntegral == null) {
            if (memberModel == null) {
                memberModel = memberService.getByAccount((AppUser) AppUserContext.getCurrentUser());
            }
            memberIntegral = memberIntegralService.getMemberIntegral(memberModel);
        }
        if (memberIntegral == null) {
            memberIntegral = new MemberIntegral();
        }
        return memberIntegral;
    }

    public Member getCriteria() {
        return criteria;
    }

    public DataModel getTableModel() {
        CriteriaTemplate c = CriteriaTemplate.forClass(Member.class);
        RestrictionTemplate r = new RestrictionTemplate(true);
        TablePage tablePage = TableContext.getTablePage();
        if (tablePage == null) {
            return new PageDataModel(new Page());
        }

        c.createCriteria("support", "s").add(r.eq("s.appUser", AppUserContext.getCurrentUser()));
        c.add(r.like("name", criteria.getName()));
        c.add(r.like("mobile", criteria.getMobile()));
        if (levelCriteria != null) {
            c.createCriteria("memberIntegral", "integral").add(Restrictions.eq("integral.memberLevel", levelCriteria));
        }
        if (groupCriteria != null) {
            c.createCriteria("memberGroups", "group").add(Restrictions.eq("group.id", groupCriteria.getId()));
        }
        if (criteria.getLoyalty() != null) {
            c.add(Restrictions.eq("loyalty", criteria.getLoyalty()));
        }
        if (criteria.getLiveness() != null) {
            c.add(Restrictions.eq("liveness", criteria.getLiveness()));
        }
        if (startDate != null && endDate == null) {
            c.add(r.gt("activeTime", startDate));
        }
        else if (startDate == null && endDate != null) {
            c.add(r.lt("activeTime", endDate));
        }
        else if (startDate != null && endDate != null) {
            c.add(r.between("activeTime", startDate, endDate));
        }
        List<TableOrder> tableOrders = TableContext.getTableOrders();
        List<Order> orders = new ArrayList<Order>();
        for (TableOrder tableOrder : tableOrders) {
            Order order = tableOrder.toOrder();
            if (order != null) {
                orders.add(order);
            }
        }
        Page page = memberService.pagedQuery(c, tablePage.getPage(), tablePage.getPageSize(), orders);
        return new PageDataModel(page);
    }

    public void updateUser() {
        memberService.updateMember(memberModel);

        addGlobalI18nMessage("crud_update_success_msg");
    }

    public void removeByIds() {
        String[] selectedIds = getSelectedIds();
        if (logger.isDebugEnabled()) {
            logger.debug("delete: " + Arrays.asList(selectedIds));
        }
    }

    private String[] getSelectedIds() {
        String[] result = getRequestParameterValues("id");
        if (result == null) {
            result = new String[0];
        }

        return result;
    }

    public void sendSms() {
        Member member = memberService.getById(memberId);
        smsService.sendMessage(member.getMobile(), smsContent);
        addGlobalI18nMessage("发送成功");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        memberId = getRequestParameter("memberId");
        reloadMember();
    }

    public void setLevelCriteria(MemberLevel levelCriteria) {
        this.levelCriteria = levelCriteria;
    }

    public MemberLevel getLevelCriteria() {
        return levelCriteria;
    }

    public MemberGroup getGroupCriteria() {
        return groupCriteria;
    }

    public void setGroupCriteria(MemberGroup groupCriteria) {
        this.groupCriteria = groupCriteria;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public void setCriteria(Member criteria) {
        this.criteria = criteria;
    }
}
